#include "StdAfx.hpp"
#include "BaseObject.hpp"
#include "Engine.hpp"

using namespace common;


BaseObject::BaseObject()
: m_PrevObject(NULL), m_NextObject(NULL)
, m_PrevUpdateObject(NULL), m_NextUpdateObject(NULL)
, m_RefCount(1)
, m_Id(0)
, m_IsOnUpdateList(false)
{
	assert(g_Engine);
	g_Engine->RegisterObject(this);
}

void BaseObject::SetName(const string &Name)
{
	if (Name == m_Name) return;
	assert(m_Name.empty());
	m_Name = Name;
	g_Engine->RegisterObjectName(this);
}

BaseObject::~BaseObject()
{
	if (m_IsOnUpdateList)
		g_Engine->RemoveObjectFromUpdateList(this);
	g_Engine->UnregisterObject(this);

	assert(m_RefCount == 0);
	//assert(m_PrevObject == NULL && m_NextObject == NULL && "Object not unregistered from Engine before destruction. Did you called destructor directly instead of Release method?");
}

void BaseObject::AddRef()
{
	m_RefCount++;
}

void BaseObject::Release(bool AllowDelete, bool DeferredDelete)
{
	assert(m_RefCount > 0);
	m_RefCount--;
	if (m_RefCount == 0 && AllowDelete)
	{
		assert(g_Engine);
		if (DeferredDelete)
			g_Engine->RegisterObjectForDeferredDelete(this);
		else
			delete this;
	}
}

void BaseObject::SetUpdate(bool v)
{
	if (v == m_IsOnUpdateList) return;
	assert(g_Engine);

	if (v)
		g_Engine->AddObjectToUpdateList(this);
	else
		g_Engine->RemoveObjectFromUpdateList(this);

	m_IsOnUpdateList = v;
}
